import { createStore } from "vuex";

// 防抖
function debounce(func, wait) {
  let timeout;
  return () => {
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      func();
    }, wait);
  };
}

// 持久化存储
function customPlugin(store) {
  const local = JSON.parse(localStorage.getItem("Vuex-State"));
  if (local) {
    store.replaceState(local);
  }
  // 每当状态发生变化的时候，会订阅
  store.subscribe((mutation, state) => {
    // 防抖
    debounce(
      () => localStorage.setItem("Vuex-State", JSON.stringify(state)),
      2000
    )();
  });
}

export default createStore({
  strict: true,
  plugins: [customPlugin],
  // 组件的状态
  state: {
    count: 0,
  },
  // 计算属性
  getters: {
    double(state) {
      return state.count * 2;
    },
  },
  // 同步更改的
  mutations: {
    add(state, payload) {
      state.count += payload;
    },
  },
  actions: {
    asyncAdd({ commit }, payload) {
      setTimeout(() => {
        commit("add", payload);
      }, 1000);
    },
  },
  modules: {
    aCount: {
      // 不加namespaced:true,默认为false,mutations和actions将不会有私有名，其它模块或主体中存在同名函数且被触发时，该模块下的同名函数也会被触发
      namespaced: true,
      state: {
        count: 0,
      },
      // 计算属性
      getters: {
        double(state) {
          return state.count * 2;
        },
      },
      // 同步更改的
      mutations: {
        add(state, payload) {
          state.count += payload;
        },
      },
      actions: {
        asyncAdd({ commit }, payload) {
          setTimeout(() => {
            commit("add", payload);
          }, 1000);
        },
      },
    },
    bCount: {
      namespaced: true,
      state: {
        count: 0,
      },
      // 计算属性
      getters: {
        double(state) {
          return state.count * 2;
        },
      },
      // 同步更改的
      mutations: {
        add(state, payload) {
          state.count += payload;
        },
      },
      actions: {
        asyncAdd({ commit }, payload) {
          setTimeout(() => {
            commit("add", payload);
          }, 1000);
        },
      },
    },
  },
});
